App({
  
  data: {

    'apiHost': 'http://www.tenement.com:81/',
    //'apiHost': 'https://www.bestsmartbee.com/',
    //'websocket': 'ws://127.0.0.1:9501',
    'mock': 0,//全局使用mock请求 
    debug: 1,
    store_id:1,
    appid: "2019070165753283",
    getUserInfoCb: [],
  },
  pageData: {},
  //
  runGetUserInfoCb: function(userInfo) {
    for (var i in this.data.getUserInfoCb) {
      var fun = this.data.getUserInfoCb[i];
      typeof fun == "function" && fun(userInfo);
    }
    this.data.getUserInfoCb = [];
  },

  loginByUserInfo: function(userInfo,cb) {
    var that = this;
    this.api("/api/user/loginByAilpayApp", userInfo, function(userRes) {
      // console.log("userRes", userRes);
      // if (userRes.code == 3 || !userRes.data.phone) {
      //   my.navigateTo({
      //     url: '/pages/user/bindphone?page=bindphone',
      //   })
      //   return false;
      // }
      if (userRes.code != 200 && userRes.code != 3) {
        that.alert(userRes.msg);
        return false;
      }
      // console.log(userRes);
      that.globalData.userInfo = userRes.data
      that.runGetUserInfoCb(that.globalData.userInfo);
      typeof cb == "function" ? cb(userRes) : '';
    });
  },

  getUserInfo: function(cb) {
    // console.log(this.data.getUserInfoCb.length);
    var that = this
    this.data.getUserInfoCb.push(cb);
    if (this.data.getUserInfoCb.length > 1) {
      return;
    }
    var user_info = this.globalData.userInfo;
    console.log(user_info);
    if (user_info) {
      this.runGetUserInfoCb(user_info);
      //typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
     
      my.getAuthCode({
        scopes: 'auth_user',
        success: (res) => {
          my.getAuthUserInfo({
            success: (userInfo) => {
              userInfo.authCode = res.authCode;
              that.loginByUserInfo(userInfo)
            }
          });
        },
        fail:function(res){
          console.log("getAuthCode:",res);
        }
      });

    }
  },
  globalData: {
    userInfo: null,
    window: {}
  },
  getShopInfo:function(){
    return { id:216}
  },
  getUrl: function(url, data) {
    var params = this.requestParam(url, data);
    var json = params.param;
    var arg = Object.keys(json).map(function(key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    }).join("&");
    console.log(params.url + "?" + arg);
    return params.url + "?" + arg + "#wechat_redirect";
  },
  //请求接口
  requestParam: function(url, data, cb) {
    var host = this.data.apiHost;
    if (url.indexOf("http") !== 0) {
      url = host + url;
    }
    var param = {};
    var cbf = cb;
    if (typeof (data) == 'function') {
      cbf = data;
    } else if (typeof (data) == 'object') {
      param = data;
    }
    this.data.debug == 1 ? param['time'] = Date.parse(new Date()) : '';

    // var extConfig = this.getExtConfigSync();
    //  console.log("extConfig", extConfig);
    param['from_alipay_app'] = 1;
    param['store_id'] = this.data.store_id;
    param['appid'] = this.data.appid;

    //param['uuid']='wx101';
    var user_info = this.globalData.userInfo && this.globalData.userInfo.token ? this.globalData.userInfo : my.getStorageSync("user_info");

    param['token'] = user_info ? user_info.token : '';
    param['runThreadKey'] = 'eee50acd6ee441d75ad2b87c9747d09b';
    console.log("param:", param);
    return {
      'param': param,
      'url': url,
      'cb': cbf,
    };
  },



  api: function(url, data = {}, cb) {
    if (url.indexOf("http") === 0) {
      var apiUrl = url;
    } else {
      var apiUrl = this.data.apiHost + url;
    }
    //console.log(this.data.mock);
    if (data['mock'] == 1 || this.data.mock == 1) {
      apiUrl = this.data.mockUrl + url;
    }
    if (data['mock'] == 0) {
      apiUrl = this.data.apiHost + url;
    }

    this.postData(apiUrl, data, cb);
  },

  showLoading:function(){
    my.showLoading();
  },
  hideLoading: function() {
    my.hideLoading();
  },
  postData: function(url, data, cb) {
    //  wx.showToast({
    //    title: '加载中...',
    //    icon: 'loading',
    //    duration: 5000
    //  });
    my.showLoading();
    var p = this.requestParam(url, data, cb);
    console.log("postData:", p);
    var method = p['param']['method'] ? p['param']['method'] : 'GET';
    // console.log("postData:");

    var cbf = p['cb'];
    my.httpRequest({
      url: p['url'],
      data: p['param'],
      method: method,
      // header: {
      //    'Content-Type': 'application/json'
      // },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: (resp) => {
        typeof (cbf) == "function" ? cbf(resp.data) : "";
        // wx.hideToast();
        my.hideLoading();
      },
      fail: (err) => {
        my.alert({
          title: "错误信息",
          content: JSON.stringify(err)
        })
      }
    });

   
  },
  //页面的数据 
  //页面的数据 
  setPageData: function(pageName, data = {}) {
    var curData = this.pageData[pageName] ? this.pageData[pageName] : {};
    // console.log("setPageData",data);
    for (var i in data) {
      //console.log("i", i, data[i]);
      curData[i] = data[i];
    }

    this.pageData[pageName] = curData;
    console.log(this.pageData);
  },
  getPageData: function(pageName, key = '') {
    var curData = this.pageData[pageName];
    if (key) {
      return curData ? curData[key] : null;
    } else {
      return curData;
    }
  },
  alert: function(content, type ="success") {
    my.showToast({
      type: type,
      content: content,
      duration: 1000
    });
  },
  onLaunch(options) {
    // 第一次打开
    // options.query == {number:1}
    this.getUserInfo(function(userInfo) {
      console.log(userInfo);
      my.setStorageSync("user_info", userInfo);
      // that.getNoti()//用户消息提醒
    });
  },
  onShow(options) {
    // 从后台被 scheme 重新打开
    // options.query == {number:1}
  },


});
